<?php

namespace app\service;

use app\dao\ProjectDao;
use think\facade\Log;
use think\Exception;

class ProjectService
{
    private $projectDao;

    public function __construct()
    {
        $this->projectDao = new ProjectDao();
    }

    // 创建竞赛项目
    public function createProject($name, $description, $adminId)
    {
        try {
            // 使用项目 DAO 层创建项目
            $project = $this->projectDao->createProject($name, $description, $adminId);

            if (!$project) {
                throw new Exception('创建竞赛项目失败');
            }

            return $project;
        } catch (\Exception $e) {
            Log::error("创建竞赛项目失败: " . $e->getMessage());
            throw new Exception('系统异常，请稍后再试');
        }
    }

    // 获取项目详情（包括成员、教师等）
    public function getProjectDetails($projectId)
    {
        try {
            $project = $this->projectDao->getProjectById($projectId);

            if (!$project) {
                throw new Exception('项目不存在');
            }

            // 获取项目相关的教师和成员信息
            $projectTeachers = $project->teachers;  // 通过模型关联获取
            $projectSkills = $project->skills;

            return [
                'project' => $project,
                'teachers' => $projectTeachers,
                'skills' => $projectSkills
            ];
        } catch (\Exception $e) {
            Log::error("获取项目详情失败: " . $e->getMessage());
            throw new Exception('系统异常，请稍后再试');
        }
    }

    // 为项目添加指导老师
    public function addTeacherToProject($projectId, $teacherId)
    {
        try {
            $result = $this->projectDao->addTeacher($projectId, $teacherId);

            if (!$result) {
                throw new Exception('添加指导老师失败');
            }

            return ['msg' => '成功添加指导老师'];
        } catch (\Exception $e) {
            Log::error("为项目添加指导老师失败: " . $e->getMessage());
            throw new Exception('系统异常，请稍后再试');
        }
    }
}
